package com.cardone.platform.common.function;

import com.cardone.common.cache.util.CacheUtils;
import com.cardone.context.ContextHolder;
import com.cardone.context.function.Execution1Function;
import com.cardone.platform.common.dto.EntityLogDto;
import com.cardone.platform.common.service.EntityLogService;
import com.cardone.security.token.dto.TokenDto;
import com.cardone.security.token.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.UUID;

/**
 * Created by c100000002 on 15-2-6.
 */
@Slf4j
public class TokenGenerateFunction implements Execution1Function<TokenDto, Map<String, Object>> {
    @Override
    public TokenDto execution(Map<String, Object> stringObjectMap) {
        String clientId = MapUtils.getString(stringObjectMap, "client_id");

        TokenDto token = new TokenDto().setId(MapUtils.getString(stringObjectMap, "id")).setClientId(clientId);
        token.setKey(StringUtils.remove(UUID.randomUUID().toString(), "-"));

        TokenUtils.remove(clientId, null);

        EntityLogDto insertEntityLog = new EntityLogDto();

        insertEntityLog.setTypeTypeCode("log_type").setTypeCode("login").setCode("login");
        insertEntityLog.setEntityId(String.valueOf(token.getId())).setId(token.getKey());
        insertEntityLog.setUserId(insertEntityLog.getEntityId()).setClientId(token.getClientId());

        EntityLogDto entityLog = ContextHolder.getBean(EntityLogService.class).saveByIdOrCode(EntityLogDto.class, insertEntityLog);

        token.setCreateDate(entityLog.getCreatedDate());

        CacheUtils.put(TokenUtils.class.getName(), token.getKey(), token);
        CacheUtils.put(clientId, TokenUtils.getTokenParamName(), token.getKey());

        return token;
    }
}
